package com.java110.accessControl.adapter.dahuatech;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dahuatech.hutool.http.Method;
import com.dahuatech.icc.oauth.http.DefaultClient;
import com.dahuatech.icc.oauth.http.IClient;
import com.dahuatech.icc.oauth.model.v202010.GeneralRequest;
import com.dahuatech.icc.oauth.model.v202010.GeneralResponse;
import com.java110.accessControl.adapter.sxoa.SxCommomFactory;
import com.java110.core.adapt.ICallAccessControlService;
import com.java110.core.factory.LocalCacheFactory;
import com.java110.core.factory.MappingCacheFactory;
import com.java110.core.factory.NotifyAccessControlFactory;
import com.java110.core.service.machine.IMachineService;
import com.java110.core.util.Assert;
import com.java110.core.util.DateUtil;
import com.java110.core.util.SeqUtil;
import com.java110.core.util.StringUtil;
import com.java110.entity.accessControl.UserFaceDto;
import com.java110.entity.fee.FeeDto;
import com.java110.entity.machine.MachineDto;
import com.java110.entity.machine.MachineFaceDto;
import com.java110.entity.openDoor.OpenDoorDto;
import com.java110.entity.response.ResultDto;
import com.java110.entity.room.RoomDto;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class DaHuaQueryAccessControlInoutLogAdapt {
    private static Logger logger = LoggerFactory.getLogger(DaHuaQueryAccessControlInoutLogAdapt.class);

    private static final String QUERY_ACCESS_CONTROL_LOG = "/evo-apigw/evo-accesscontrol/1.0.0/card/accessControl/swingCardRecord/bycondition/combined";

    @Autowired
    private ICallAccessControlService callAccessControlServiceImpl;

    private static String consumerId = "";

    public static final String OPEN_TYPE_FACE = "1000"; // 人脸开门

    @Autowired
    private RestTemplate outRestTemplate;


    @Autowired
    private IMachineService machineServiceImpl;


    public void query() {

        try {
            IClient iClient = new DefaultClient();
//        JSONObject postParameters = new JSONObject();
//        postParameters.put("consumerId", consumerId);
//        postParameters.put("autoCommit", true);
//
//        String paramOutString = HttpClient.doPost(url, postParameters.toJSONString(), "Bearer " + getToken(), "POST");

            //添加设备
            JSONObject paramIn = new JSONObject();
            paramIn.put("pageNum", 1);
            paramIn.put("pageSize", 20);
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MINUTE, -1);
            paramIn.put("startSwingTime", DateUtil.getFormatTimeString(calendar.getTime(), DateUtil.DATE_FORMATE_STRING_A));
            paramIn.put("endSwingTime", DateUtil.getFormatTimeString(new Date(), DateUtil.DATE_FORMATE_STRING_A));


            GeneralRequest generalRequest = new GeneralRequest(QUERY_ACCESS_CONTROL_LOG, Method.POST);
            generalRequest.body(paramIn.toJSONString());
            GeneralResponse generalResponse = iClient.doAction(generalRequest, generalRequest.getResponseClass());
            if (!generalResponse.isSuccess()) {
                return ;
            }

           JSONObject outParam = JSONObject.parseObject(generalResponse.getResult());
            if (!outParam.containsKey("data")) {
                return ;
            }

            JSONArray pageData = outParam.getJSONObject("data").getJSONArray("pageData");

            JSONObject dataObj = null;
            JSONObject content = null;
            for (int dataIndex = 0; dataIndex < pageData.size(); dataIndex++) {
                dataObj = pageData.getJSONObject(dataIndex);
                httpFaceResult(dataObj);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public String httpFaceResult(JSONObject content) {
        ICallAccessControlService notifyAccessControlService = NotifyAccessControlFactory.getCallAccessControlService();
        JSONObject resultParam = new JSONObject();
        List<MachineDto> machineDtos = null;
        try {
            JSONObject body = content;

            MachineDto machineDto = new MachineDto();
            machineDto.setMachineCode(body.getString("deviceCode"));
            machineDtos = callAccessControlServiceImpl.queryMachines(machineDto);

            Assert.listOnlyOne(machineDtos, "设备不存在");

            String userId = body.containsKey("personCode") ? body.getString("personCode") : "";
            String userName = "";
            String createTime = "";
            if (!StringUtils.isEmpty(userId)) {
                MachineFaceDto machineFaceDto = new MachineFaceDto();
                machineFaceDto.setExtUserId(userId);
                machineFaceDto.setMachineId(machineDtos.get(0).getMachineId());
                List<MachineFaceDto> machineFaceDtos = notifyAccessControlService.queryMachineFaces(machineFaceDto);
                if (machineFaceDtos != null && machineFaceDtos.size() > 0) {
                    userName = machineFaceDtos.get(0).getName();
                    userId = machineFaceDtos.get(0).getUserId();
                }
            } else {
                userName = body.getString("personName");
            }
            if (StringUtil.isEmpty(userId)) {
                userId = "-1";
            }
            if (StringUtil.isEmpty(userName)) {
                userName = body.getString("personName");
            }
            if (StringUtil.isEmpty(userName)) {
                userName = "门禁未上报";
            }

            createTime = body.getString("swingTime");

            OpenDoorDto openDoorDto = new OpenDoorDto();
            //openDoorDto.setFace(ImageFactory.encodeImageToBase64(body.getString("orPrintscreen")));
            openDoorDto.setFace(body.getString("recordImage"));
            openDoorDto.setUserName(userName);
            openDoorDto.setHat("3");
            openDoorDto.setMachineCode(machineDtos.get(0).getMachineCode());
            openDoorDto.setUserId(userId);
            openDoorDto.setOpenId(SeqUtil.getId());
            openDoorDto.setOpenTypeCd(OPEN_TYPE_FACE);
            openDoorDto.setSimilarity("1");
            openDoorDto.setCreateTime(createTime);
            freshOwnerFee(openDoorDto);

            notifyAccessControlService.saveFaceResult(openDoorDto);

        } catch (Exception e) {
            logger.error("推送人脸失败", e);
        }
        resultParam.put("result", 1);
        resultParam.put("success", true);
        return resultParam.toJSONString();//未找到设备

    }


    /**
     * 查询费用信息
     *
     * @param openDoorDto
     */
    protected void freshOwnerFee(OpenDoorDto openDoorDto) {

        ICallAccessControlService notifyAccessControlService = NotifyAccessControlFactory.getCallAccessControlService();
        List<FeeDto> feeDtos = new ArrayList<>();
        try {
            //查询业主房屋信息
            UserFaceDto userFaceDto = new UserFaceDto();
            userFaceDto.setUserId(openDoorDto.getUserId());
            List<RoomDto> roomDtos = notifyAccessControlService.getRooms(userFaceDto);

            if (roomDtos == null || roomDtos.size() < 1) {
                return;
            }

            for (RoomDto roomDto : roomDtos) {
                List<FeeDto> tmpFeeDtos = notifyAccessControlService.getFees(roomDto);
                if (tmpFeeDtos == null || tmpFeeDtos.size() < 1) {
                    continue;
                }
                feeDtos.addAll(tmpFeeDtos);
            }
        } catch (Exception e) {
            logger.error("云端查询物业费失败", e);
        }

        if (feeDtos.size() < 1) {
            openDoorDto.setAmountOwed("0");
            return;
        }
        double own = 0.00;
        for (FeeDto feeDto : feeDtos) {
            logger.debug("查询费用信息" + JSONObject.toJSONString(feeDto));
            own += feeDto.getAmountOwed();
        }

        openDoorDto.setAmountOwed(own + "");
    }
}
